<template>
  <view class="padding-bottom-button">
    <l-background has-sub-background />
    <view class="padding-30">
      <view class="card">
        <l-form-cell label="产品" label-width="auto" has-slot unlined>
          <picker mode="selector" class="margin-right-24" style="width:100%;" :value="productIndex" :range="productList" range-key="name" @change="bindProduct">
            <view class="form-item flex-row align-center justify-end">
              <text class="text-30 color-t1 text-overflow-one text-right">{{ productList[productIndex].name }}</text>
            </view>
          </picker>
        </l-form-cell>
      </view>
      <view class="card margin-top-16">
        <l-form-cell
          v-for="(item,index) in vehicleTypeList"
          :key="index"
          v-model="item.price"
          :label="item.brand"
          placeholder="0-10000"
          type="digit"
          suffix="元"
        />
        <l-form-cell label="开始时间" must has-slot @click="changeDate('startDate')">
          <text class="text-30" :class="['color-t' + (form.startDate ? 1 : 3)]">{{ form.startDate || '请选择日期' }}</text>
        </l-form-cell>
        <l-form-cell label="结束时间" must has-slot unlined @click="changeDate('endDate')">
          <text class="text-30" :class="['color-t' + (form.endDate ? 1 : 3)]">{{ form.endDate || '请选择日期' }}</text>
        </l-form-cell>
      </view>
    </view>

    <tui-datetime ref="dateTime" :type="2" :end-year="2100" :set-date-time="setDateTime" @confirm="setDate" />

    <safe-area-bottom />
    <l-bottom-button text="确定" @click="setProductPrice" />
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import { dateFormat, formVerify, checkDate, loading } from '@/common/util'
import { getProductList, getProductPriceList } from '@/common/api/car'
import { getCarType, updateAllProductsPrice } from '../api'
export default {
  name: 'SetAllPrice',
  data() {
    return {
      productList: [
        { name: '' }
      ],
      productIndex: 0,
      productId: '',
      vehicleTypeList: [],
      defaultPriceList: [],
      currentPage: 1,
      form: {
        startDate: '',
        endDate: ''
      },
      set: '',
      setDateTime: '',
      verifyList: [
        { attr: 'startDate', toast: '请选择开始时间' },
        { attr: 'endDate', toast: '请选择结束时间' }
      ],
      loading: null
    }
  },
  computed: {
    ...mapGetters({
      userId: 'userId'
    })
  },
  onLoad(e) {
    this.productId = e.id
  },
  created() {
    this.getProductList()
  },
  methods: {
    // 获取产品列表
    async getProductList() {
      this.loading = loading('加载中')
      const [err, res] = await getProductList({
        current: 1,
        size: 9999,
        type: 0
      })
      if (!this.$http.errorCheck(err, res)) return false
      console.log(res)
      this.productList = res.data.data
      if (!this.productId) {
        this.productId = this.productList[0].id
        this.productIndex = 0
      } else {
        const idx = this.productList.findIndex(item => {
          return item.id == this.productId
        })
        if (idx >= 0) {
          this.productIndex = idx
        }
      }
      await this.getProductDefaultPrice()
    },
    // 查询已有车型的产品价格
    async getProductDefaultPrice() {
      this.defaultPriceList = []
      const [err, res] = await getProductPriceList({
        vehicleTypeId: 0,
        productId: this.productId,
        page: this.currentPage,
        defaultPrice: 1
      })
      if (!this.$http.errorCheck(err, res)) return false

      const defaultPriceList = res.data.data
      if (defaultPriceList.length < 20) {
        this.defaultPriceList = this.defaultPriceList.concat(defaultPriceList)
      } else {
        this.defaultPriceList = this.defaultPriceList.concat(defaultPriceList)
        this.currentPage++
        this.getProductDefaultPrice()
      }
      this.getVehicleTypeList()
    },
    // 获取车型列表
    async getVehicleTypeList() {
      this.vehicleTypeList = []
      const [err, res] = await getCarType(this.userId)
      this.loading.hide()
      if (!this.$http.errorCheck(err, res)) return false
      const vehicleTypeList = res.data.data
      if (vehicleTypeList.length > 0) {
        for (let i = 0; i < vehicleTypeList.length; i++) {
          vehicleTypeList[i].brand = vehicleTypeList[i].brand + vehicleTypeList[i].seatAmount + '+1座'
          const defaultPriceList = this.defaultPriceList
          for (let j = 0; j < defaultPriceList.length; j++) {
            if (vehicleTypeList[i].id === defaultPriceList[j].vehicleTypeId) {
              vehicleTypeList[i].price = defaultPriceList[j].price
              break
            }
          }
          if (vehicleTypeList[i].price == 0) {
            vehicleTypeList[i].price = ''
          }
        }
        this.vehicleTypeList = vehicleTypeList
      } else {
        this.toast('暂无车型,请添加车型', () => {
          this.jump()
        })
      }
    },
    // 设置选中产品
    bindProduct(e) {
      this.productIndex = e.detail.value
      this.productId = this.productList[e.detail.value].id
      this.getProductDefaultPrice()
    },
    // 显示修改时间
    changeDate(attr) {
      this.setDateTime = this.form[attr] || dateFormat()

      if (this.set !== attr) this.$refs.dateTime.initData()

      this.set = attr
      this.$refs.dateTime.show()
    },
    // 确认修改时间
    setDate(e) {
      this.form[this.set] = e.result
      checkDate(this.form.startDate, this.form.endDate)
    },
    // 设置产品的价格
    async setProductPrice() {
      if (formVerify(this.form, this.verifyList) && checkDate(this.form.startDate, this.form.endDate)) {
        const l = loading('加载中')
        const prices = []
        for (let i = 0; i < this.vehicleTypeList.length; i++) {
          prices.push({
            'vehicleTypeId': this.vehicleTypeList[i].id,
            'price': this.vehicleTypeList[i].price,
            'productId': this.productId,
            'startDate': this.form.startDate,
            'endDate': this.form.endDate
          })
        }
        const [err, res] = await updateAllProductsPrice({
          userId: this.userId,
          prices,
          defaultPrice: 1
        })
        l.hide()
        if (!this.$http.errorCheck(err, res)) return false

        this.toast('设置成功', () => {
          this.jump()
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
